package com.company.aicrawlers.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.company.aicrawlers.entity.CollectResult;
import com.company.aicrawlers.mapper.CollectResultMapper;
import com.company.aicrawlers.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 采集结果 Service实现类
 * 
 * @author AI Crawlers
 * @since 2025-10-10
 */
@Slf4j
@Service
public class CollectResultServiceImpl extends ServiceImpl<CollectResultMapper, CollectResult> 
        implements CollectResultService {

    @Autowired
    private CollectTaskQuestionPlatformService taskQuestionPlatformService;

    @Autowired
    private CollectTaskQuestionService taskQuestionService;

    @Autowired
    private CollectTaskPlatformService taskPlatformService;

    @Autowired
    private CollectTaskService collectTaskService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveResult(CollectResult result) {
        // 设置创建时间
        if (result.getCreateTime() == null) {
            result.setCreateTime(LocalDateTime.now());
        }

        // ⭐ 检查是否已存在（防止重复采集）
        // 唯一索引: uk_task_question_platform (task_id, question_id, platform_name)
        if (result.getTaskId() != null && result.getTaskId() > 0 
                && result.getQuestionId() != null && result.getPlatformName() != null) {
            
            LambdaQueryWrapper<CollectResult> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CollectResult::getTaskId, result.getTaskId())
                   .eq(CollectResult::getQuestionId, result.getQuestionId())
                   .eq(CollectResult::getPlatformName, result.getPlatformName());
            
            CollectResult existing = this.getOne(wrapper);
            
            if (existing != null) {
                log.warn("采集结果已存在，更新而非新增, taskId={}, questionId={}, platform={}", 
                        result.getTaskId(), result.getQuestionId(), result.getPlatformName());
                
                // 更新现有记录
                result.setResultId(existing.getResultId());
                result.setCreateTime(existing.getCreateTime());  // 保留创建时间
                this.updateById(result);
                
                log.info("采集结果已更新, resultId={}, taskId={}, questionId={}, platform={}", 
                        result.getResultId(), result.getTaskId(), result.getQuestionId(), result.getPlatformName());
            } else {
                // 新增记录
                this.save(result);
                log.info("采集结果已保存（新增）, resultId={}, taskId={}, questionId={}, platform={}", 
                        result.getResultId(), result.getTaskId(), result.getQuestionId(), result.getPlatformName());
            }
        } else {
            // taskId=0的自动采集，直接保存（可能重复）
            this.save(result);
            log.info("采集结果已保存（自动采集）, resultId={}, platform={}", 
                    result.getResultId(), result.getPlatformName());
        }
        
        log.info("采集结果已保存, resultId={}, taskId={}, questionId={}, platform={}, status={}", 
                result.getResultId(), result.getTaskId(), result.getQuestionId(), 
                result.getPlatformName(), result.getCollectStatus());

        // ⭐ 判断是否是任务采集（taskId > 0 表示是任务采集，taskId = 0 表示是自动采集）
        if (result.getTaskId() == null || result.getTaskId() <= 0) {
            log.info("非任务采集（自动采集），跳过任务状态更新");
            return;
        }

        boolean success = "success".equals(result.getCollectStatus());

        // 更新问句-平台执行状态
        taskQuestionPlatformService.updateExecuteStatus(
                result.getTaskId(),
                result.getQuestionId(),
                result.getPlatformName(),
                success ? "success" : "failed",
                result.getErrorMessage()
        );

        // 更新问句的完成平台数
        if (success) {
            taskQuestionService.updateCompletedPlatformCount(result.getTaskId(), result.getQuestionId());
        }

        // 更新平台统计
        taskPlatformService.updatePlatformStats(result.getTaskId(), result.getPlatformName(), success);

        // 更新任务的成功/失败次数
        if (success) {
            collectTaskService.update()
                    .setSql("success_count = success_count + 1")
                    .eq("task_id", result.getTaskId())
                    .update();
        } else {
            collectTaskService.update()
                    .setSql("fail_count = fail_count + 1")
                    .eq("task_id", result.getTaskId())
                    .update();
        }

        // 更新任务整体进度
        collectTaskService.updateTaskProgress(result.getTaskId());

        log.info("任务状态更新成功, taskId={}, questionId={}, platform={}, status={}", 
                result.getTaskId(), result.getQuestionId(), result.getPlatformName(), result.getCollectStatus());
    }

    @Override
    public List<CollectResult> getByTaskId(Long taskId) {
        LambdaQueryWrapper<CollectResult> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CollectResult::getTaskId, taskId);
        wrapper.orderByAsc(CollectResult::getQuestionId);
        wrapper.orderByAsc(CollectResult::getPlatformName);
        return this.list(wrapper);
    }

    @Override
    public List<CollectResult> compareResults(Long taskId, Long questionId) {
        LambdaQueryWrapper<CollectResult> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CollectResult::getTaskId, taskId);
        wrapper.eq(CollectResult::getQuestionId, questionId);
        wrapper.orderByAsc(CollectResult::getPlatformName);
        return this.list(wrapper);
    }
}

